/**
 * Copyright (C) 2010 David Simonek <dafesimonek@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.dafe.partyband.gui.imports;

import java.awt.Component;
import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.dafe.partyband.db.api.IBandModelFactory;
import org.dafe.partyband.db.api.DbManager;
import org.dafe.partyband.importer.api.IDirectoryScanner;
import org.dafe.partyband.importer.api.IImportRecipe;
import org.dafe.partyband.importer.api.IImporterServices;
import org.dafe.partyband.importer.api.INameEncoder;
import org.dafe.partyband.importer.api.ISongImporter;
import org.openide.WizardDescriptor;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import org.openide.util.RequestProcessor;

public class DetailsWizardPanel implements WizardDescriptor.FinishablePanel {
    public static final String RESULT = "RECIPE";

    private volatile boolean prepareCompleted = false;

    /**
     * The visual component that displays this panel. If you need to access the
     * component from this class, just use getComponent().
     */
    private DetailsPanel detailsPanel;

    private static final RequestProcessor RP = new RequestProcessor("DetailsPanel");

    // Get the visual component for the panel. In this template, the component
    // is kept separate. This can be more efficient: if the wizard is created
    // but never displayed, or not all panels are displayed, it is better to
    // create only those which really need to be visible.
    @Override
    public Component getComponent() {
        if (detailsPanel == null) {
            detailsPanel = new DetailsPanel(this);
        }
        return detailsPanel;
    }

    @Override
    public HelpCtx getHelp() {
        // Show no Help button for this panel:
        return HelpCtx.DEFAULT_HELP;
        // If you have context help:
        // return new HelpCtx(SampleWizardPanel1.class);
    }

    @Override
    public boolean isValid() {
        return true;
        // If it depends on some condition (form filled out...), then:
        // return someCondition();
        // and when this condition changes (last form field filled in...) then:
        // fireChangeEvent();
        // and uncomment the complicated stuff below.
    }

    private final Set<ChangeListener> listeners = new HashSet<ChangeListener>(1); // or can use ChangeSupport in NB 6.0

    @Override
    public final void addChangeListener(ChangeListener l) {
        synchronized (listeners) {
            listeners.add(l);
        }
    }

    @Override
    public final void removeChangeListener(ChangeListener l) {
        synchronized (listeners) {
            listeners.remove(l);
        }
    }

    protected final void fireChangeEvent() {
        Iterator<ChangeListener> it;
        synchronized (listeners) {
            it = new HashSet<ChangeListener>(listeners).iterator();
        }
        ChangeEvent ev = new ChangeEvent(this);
        while (it.hasNext()) {
            it.next().stateChanged(ev);
        }
    }

    // You can use a settings object to keep track of state. Normally the
    // settings object will be the WizardDescriptor, so you can use
    // WizardDescriptor.getProperty & putProperty to store information entered
    // by the user.
    @Override
    public void readSettings(Object settings) {
        prepareCompleted = false;
        WizardDescriptor wd = (WizardDescriptor)settings;
        final File importDir = (File)wd.getProperty(ChooseWizardPanel.IMPORT_DIR);
        final boolean isCorrect = (Boolean)wd.getProperty(ChooseWizardPanel.CORRECT);

        RP.post(new Runnable() {
            @Override
            public void run() {
                prepareImport(importDir, isCorrect);
            }
        });
    }

    @Override
    public void storeSettings(Object settings) {
        WizardDescriptor wd = (WizardDescriptor)settings;
        wd.putProperty(RESULT, detailsPanel.getResult());
    }

    private void prepareImport(File importDir, boolean isCorrect) {
        assert !SwingUtilities.isEventDispatchThread();

        IBandModelFactory factory = Lookup.getDefault().lookup(IBandModelFactory.class);
        final IImporterServices services = Lookup.getDefault().lookup(IImporterServices.class);
        ISongImporter importer = services.getSongImporter();
        importer = services.getSongImporter();
        importer.setDbFactory(factory);
        IDirectoryScanner scanner = services.getDirectoryScanner();
        INameEncoder encoder = services.getNameEncoder();
        scanner.setEncoder(encoder);
        importer.setDirectoryScanner(scanner);
        importer.setNameEncoder(encoder);
        importer.setMimeTypeDetector(services.getMimeDetector());
        //importer.setEchoNestAPI(new EchoNestAPI("TJ4BWDCARZUC69NLX"));
        if (isCorrect) {
            importer.setTitleCorrector(services.getTitleCorrector());
        }

        scanner.setDirectory(importDir);

        importer.setDbManager(DbManager.getBandManager());
        final IImportRecipe recipe = importer.prepare();

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                detailsPanel.showImport(recipe, services.getMimeDetector());
                prepareCompleted = true;
            }
        });
    }

    public boolean isFinishPanel() {
        return prepareCompleted;
    }


}
